<?php
declare(strict_types=1);

namespace App\Repository\Web;

use App\Model\Article;

class ArticleRepository
{

    public function find(int $id): Article
    {
        return Article::find($id);
    }

    public function save(Article $article)
    {
        $article->save();
        return $article;
    }

    public function findUserDraft(int $id, int $uid): ?Article
    {
        return Article::where('user_id', $uid)
            ->where('id', $id)
            ->where('status', 'draft')
            ->first();
    }

    public function create(array $data, int $userId): Article
    {
        return Article::create(array_merge($data, [
            'user_id' => $userId,
        ]));
    }

    public function getPage(array $params, string $order, string $direction, ?int $authUserId, int $page, int $perPage)
    {
        return Article::with(['user:id,name,avatar'])
            ->when(isset($params['tags']), function ($query) use ($params) {
                $query->whereHas('tags', function ($query) use ($params) {
                    $query->whereIn('name', $params['tags']);
                });
            })
            ->when(isset($params['categories']), function ($query) use ($params) {
                $query->whereHas('categories', function ($query) use ($params) {
                    $query->whereIn('name', $params['categories']);
                });
            })
            ->when(isset($params['author']), function ($query) use ($params) {
                $query->whereHas('user', function ($query) use ($params) {
                    $query->where('name', $params['author']);
                });
            })
            ->orWhere('status', 'published')
            ->orWhere('user_id', $authUserId)
            ->orderBy($order, $direction)
            ->paginate($perPage, ['id', 'user_id', 'title', 'slug', 'summary', 'content_type', 'cover_image', 'status', 'view_count', 'like_count', 'comment_count', 'favorite_count', 'reading_time', 'published_at', 'created_at', 'updated_at'], page: $page);
    }

    public function incrementViewCount(Article $article)
    {
        $article->view_count += 1;

        return $this->save($article);
    }
}